package com.hw.dao.utils;

import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;


/**
 * 分页查询DAO基础
 * @author Taoshide
 *
 */
@Repository
public class MySQLPageDaoBase extends JdbcTemplate {
	@Resource
	private DataSource dataSource;

	/**
	 * 分页查询记录
	 * @param sql
	 * @param pages
	 * @param rowMapper
	 * @param args
	 * @return
	 */
	public <X> Page<X> queryEntityForPage(String sql,Page<X> pages,RowMapper<X> rowMapper,Object...args){
		StringBuffer pageSQL = new StringBuffer("SELECT * FROM ( "+sql+" ) _pagesql " );
		//设置排序
		if(!StringUtils.isBlank(pages.getOrderBy())){
			pageSQL.append(" ORDER BY "+pages.getOrderBy());
		}
		//设置排序方向
		if(!StringUtils.isBlank(pages.getOrder())){
			pageSQL.append(" "+pages.getOrder());
		}
		//设置分页LIMIT 
		pageSQL.append(" LIMIT "+(pages.getFirst()-1)+","+pages.getPageSize() );
		
		List<X> resultList = super.query(pageSQL.toString(), args, rowMapper);
		pages.setRows(resultList);
		
		if(pages.getTotal() ==-1){
			pages.setTotal(this.findCountTotal(sql, args));
		}
		
		return pages;
	}
	
	/**
	 * 查询记录总数
	 * @param sql
	 * @param args
	 * @return
	 */
	private int findCountTotal(String sql,Object...args){
		//判断当前是否有总记录数，如果没有，则查询一次总记录数
		String selectCountSQL = "select count(1) from ("+sql+") _pagesql";
		return super.queryForInt(selectCountSQL, args);
	}
	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
}
